//对比两个对象是否相等
const deepCompare = function (x, y) {
    var i, l, leftChain, rightChain;

    function compare2Objects(x, y) {
        var p;

        // remember that NaN === NaN returns false
        // and isNaN(undefined) returns true
        if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
            return true;
        }

        // Compare primitives and functions.
        // Check if both arguments link to the same object.
        // Especially useful on the step where we compare prototypes
        if (x === y) {
            return true;
        }

        // Works in case when functions are created in constructor.
        // Comparing dates is a common scenario. Another built-ins?
        // We can even handle functions passed across iframes
        if ((typeof x === 'function' && typeof y === 'function') ||
            (x instanceof Date && y instanceof Date) ||
            (x instanceof RegExp && y instanceof RegExp) ||
            (x instanceof String && y instanceof String) ||
            (x instanceof Number && y instanceof Number)) {
            return x.toString() === y.toString();
        }

        // At last checking prototypes as good as we can
        if (!(x instanceof Object && y instanceof Object)) {
            return false;
        }

        if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
            return false;
        }

        if (x.constructor !== y.constructor) {
            return false;
        }

        if (x.prototype !== y.prototype) {
            return false;
        }

        // Check for infinitive linking loops
        if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
            return false;
        }

        // Quick checking of one object being a subset of another.
        // todo: cache the structure of arguments[0] for performance
        for (p in y) {
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            } else if (typeof y[p] !== typeof x[p]) {
                return false;
            }
        }

        for (p in x) {
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            } else if (typeof y[p] !== typeof x[p]) {
                return false;
            }

            switch (typeof (x[p])) {
                case 'object':
                case 'function':

                    leftChain.push(x);
                    rightChain.push(y);

                    if (!compare2Objects(x[p], y[p])) {
                        return false;
                    }

                    leftChain.pop();
                    rightChain.pop();
                    break;

                default:
                    if (x[p] !== y[p]) {
                        return false;
                    }
                    break;
            }
        }

        return true;
    }

    if (arguments.length < 1) {
        return true; //Die silently? Don't know how to handle such case, please help...
        // throw "Need two or more arguments to compare";
    }

    for (i = 1, l = arguments.length; i < l; i++) {

        leftChain = []; //Todo: this can be cached
        rightChain = [];

        if (!compare2Objects(arguments[0], arguments[i])) {
            return false;
        }
    }

    return true;
}


// 找出两个数组中不同的 返回数组
const getArrDifference = (arr1, arr2) => {
    return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
    });
}

//数组中去除NaN
const deleteNaN = (arr) => {
    var res = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === arr[i]) {
            res.push(arr[i]);
        }
    }
    return res
}

//地址判断
const getDoMain = () => {
    let baseUrl = 'http://127.0.0.1:6020/';
    console.log(document.domain)
    if (document.domain == 'https://wxopen.grzq.xyz') {
    //     // baseUrl = 'http://talk_dev.jiudoujishi.com/';
    //     // baseUrl = 'http://develop.v1.kykykb.cn:7080/';
        baseUrl = 'https://wxopen.grzq.xyz/';
    // } else if (document.domain == 'v1.kykykb.cn') {
    //     baseUrl = 'https://v1.kykykb.cn/';
    // } else if (document.domain == 'localhost') {
    //     // baseUrl = 'http://bj.jiudoujishi.com/';
    //     // baseUrl = 'http://talk_dev.jiudoujishi.com/';
    //     // baseUrl = 'http://develop.v1.kykykb.cn:7080/';
    } else {
      baseUrl = 'http://127.0.0.1:6020/';
    }
    console.log(baseUrl)
    return baseUrl;
    // return 'https://grzq.wajx.top/';
}

const getWsDoMain = () => {
    var baseUrl = 'https://wxopen.grzq.xyz/';

    return baseUrl;
}



const parseTime = (time, cFormat) => {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}


const _empty = (v) => {
    let tp = typeof v,
        rt = false;
    if (tp == "number" && String(v) == "") {
        rt = true
    } else if (tp == "undefined") {
        rt = true
    } else if (tp == "object") {
        if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true
    } else if (tp == "string") {
        if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
    } else if (tp == "function") {
        rt = false
    }
    return rt
}

//时间戳转 年-月-日
const stampToDate = (value) => {
    value = value * 1000;
    let date = new Date(value);
    //注意对方给你的是毫秒还是秒，如果是毫秒需要转秒（*1000）=> todo提供10位秒的时间戳
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? "0" + MM : MM;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    let m = date.getMinutes();
    m = m < 10 ? "0" + m : m;
    let s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    if (value) {
        return y + "-" + MM + "-" + d;
    }
}




//时间戳转 年-月-日 时：分：秒  参数value为10位时间戳
const stampToDateTime = (value) => {
    value = value * 1000;
    let date = new Date(value);
    //注意对方给你的是毫秒还是秒，如果是毫秒需要转秒（*1000）=>  todo提供10位秒的时间戳
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? "0" + MM : MM;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    let m = date.getMinutes();
    m = m < 10 ? "0" + m : m;
    let s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
}

//提取字符串中符合正则的字符 返回数组
const extractTransform = (str) => {
    // let newStr = null; //返回值
    // const regs = /([0-9]{3,4}-)?[0-9]{7,8}|(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})/g; //此正则是不加区号的也会显示，但是会影响到后面的手机号正则
    const regs = /([0-9]{3,4}-)[0-9]{7,8}|(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})/g; //此正则只显示加区号的座机号，并且手机号限制在12位 多或少都不会匹配到；
    // const num = str.replace(/\s|[(]|[)]|[（]|[）]|[-]*/g, ''); //去除字符串中所有空格、小括号和横杠
    const num = str.replace(/\s/g, '');//去除所有空格
    const phone = str.match(regs); //识别手机号或者固话（在字符串内检索指定的值，或找到一个或多个正则表达式的匹配）
    // phone && (newStr = phone.join(',')); //有值的话得到一个数组，用空格隔开转化为字符串
    // return newStr;
    return phone;
}

const today = () => { //获取当前时间戳
	var timestamp = parseInt(new Date().getTime() / 1000); // 当前时间戳 10位 如果是13位则 删除 / 1000 即可
	return timestamp;
}

//获取当前年
const getCurrentYear = () => {
	return new Date().getFullYear();
}

//获取当前月
const getCurrentMonth = () => {
	var currentDate = new Date();
	var currentMonth = currentDate.getMonth() + 1;
	return currentMonth;
}




// 以下4个方法配合处理 =》 根据毫秒级时间戳获取计算当前时间后的显示 用于聊天页面
// 一分钟内 = 刚刚
// 一小时内 = xx分钟之前
// 今日 = 时：分
// 今天之前当年内 = 月-日 时：分
// 不属于当年 = 年-月-日 时：分

function formatDateTime(timeValue) { //参数为13位时间戳
    var date = new Date(timeValue);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second; //这里注意由于把上行的 - 替换成中文 年月日  所以会导致下面timeChange方法中的substr的位数，之后如果替换为- 则需要对应修改timechange中的substr位数
};

//判断传入日期是否为昨天
function isYestday(timeValue) { //参数为13位时间戳
    var date = (new Date());
    //当前时间
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
    //今天凌晨
    var yestday = new Date(today - 24 * 3600 * 1000).getTime();
    return timeValue < today && yestday <= timeValue;
};

//判断传入日期是否属于今年
function isYear(timeValue) { //参数为13位时间戳
    var takeNewYear = formatDateTime(new Date()).substr(0, 4);
    //当前时间的年份
    var takeTimeValue = formatDateTime(timeValue).substr(0, 4);
    //传入时间的年份
    return takeTimeValue == takeNewYear;
}

//60000 1分钟 //3600000 1小时 //86400000 24小时 //对传入时间进行时间转换
const timeChange = (timeValue) => { //参数为13位时间戳
    var timeNew = Date.parse(new Date());
    //当前时间
    var timeDiffer = timeNew - timeValue;
    //与当前时间误差 var returnTime = '';
    if (timeDiffer <= 60000) {
        //一分钟内
        var returnTime = '刚刚';
    } else if (timeDiffer > 60000 && timeDiffer < 3600000) {
        //1小时内
        var returnTime = Math.floor(timeDiffer / 60000 )+ '分钟前';
    } else if (timeDiffer >= 3600000 && timeDiffer < 86400000 && isYestday(timeValue) === false) {
        //今日
        var returnTime = formatDateTime(timeValue).substr(12, 5);
    } else if (timeDiffer > 3600000 && isYestday(timeValue) === true) {
        //昨天
        // var returnTime = '昨天' + formatDateTime(timeValue).substr(11, 5);
        var returnTime = formatDateTime(timeValue).substr(5, 12);
    } else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === true) {
        //今年
        var returnTime = formatDateTime(timeValue).substr(5, 12);
    } else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === false) {
        //不属于今年
        var returnTime = formatDateTime(timeValue).substr(0, 17); //这里目前的需求只需要显示到分即可,所以暂时substr 0,16 如果需要精确到秒则 substr 0,20
    }
    return returnTime;
}

// 以上4个方法配合处理 =》 根据毫秒级时间戳获取计算当前时间后的显示 用于聊天页面

const  formatNumber= (timeValue,d=3) => {
    return timeValue.toFixed(d);
}


export default {
    deepCompare,
    getArrDifference,
    deleteNaN,
    getDoMain,
    parseTime,
    getWsDoMain,
    _empty,
    stampToDate,
    stampToDateTime,
    extractTransform,
    timeChange,
    today,
    getCurrentYear,
    formatNumber,
    getCurrentMonth
}
